import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'package:xapp_utils/xapp_utils.dart';

class DownloadUtils {
  static DownloadUtils? _instance;

  static DownloadUtils getInstance() {
    if (_instance == null) {
      _instance = new DownloadUtils._();
    }
    return _instance!;
  }

  DownloadUtils._();

  /// 下载文件
  Future<String> download(String url, [String? saveName]) async {
    try {
      if (saveName == null) {
        String ext = '';
        var extIndex = url.lastIndexOf('.');
        if (extIndex > -1) {
          ext = url.substring(extIndex);
        }
        String name = XAppUtils.getInstance().md5("66$url");
        saveName = "$name$ext";
      }

      String dir = (await getTemporaryDirectory()).path;
      String path = "$dir/download/";
      String filePath = "$path$saveName";
      File file = File(filePath);
      Directory directory = Directory(path);
      if (!directory.existsSync()) {
        directory.create();
      }
      if (file.existsSync()) {
        return file.path;
      }
      var response = await Dio()
          .get(url, options: Options(responseType: ResponseType.bytes));
      Uint8List bytes = Uint8List.fromList(response.data);

      await file.writeAsBytes(bytes);
      return file.path;
    } catch (e) {
      return '';
    }
  }
}
